import axios from 'axios';
import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
// 创建axios实例
const apiConfig = axios.create({
  baseURL: 'http://127.0.0.1:9999',
  timeout: 1000,
  headers: {
    'Content-Type': 'application/json',
   }
});

// 请求拦截器
apiConfig.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 可添加 token
    const token = sessionStorage.getItem('token');
    if (token && config.headers) {
      config.headers['satoken'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiConfig.interceptors.response.use(
  (response: AxiosResponse) => {
    // 根据后端响应结构做统一处理
    const res = response.data;//解构response
    // 统一判断 code 是否为 200
    if (res.code !== 200) {
      console.error('请求失败:', res.message || '未知错误');
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      return res;
    }
  },
  (error) => {
    console.error('网络错误:', error.message);
    return Promise.reject(error);
  }
);

// 封装 api  方法
const api = {
  get<T = any>(url: string, config?: any): Promise<T> {
    return apiConfig.get(url, config);
  },
  post<T = any>(url: string, data?: any): Promise<T> {
    return apiConfig.post(url, data);
  },
  put<T = any>(url: string, data?: any): Promise<T> {
    return apiConfig.put(url, data);
  },
  delete<T = any>(url: string, config?: any): Promise<T> {
    return apiConfig.delete(url, config);
  },
};

export default api;